<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport"
        content="width=device-width, initial-scale=1.0,minimum-scale=1,maximum-scale=1,user-scalable=no" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <!-- <link rel="stylesheet" type="text/css" href="css/index.css">
    <script type="text/javascript" src="js/index.js"></script>
    <style type="text/css"></style> -->
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .cart {
            margin: 20px auto;
            text-align: center;
            width: 500px;
        }

        ul,
        li {
            list-style: none;
        }

        form {
            width: 500px;
            margin: 0 auto;
        }

        .cart tbody tr td:nth-child(1) {
            text-align: left;
        }

        .cart thead tr th:nth-child(1) {
            text-align: left;
        }
        .numBtn{
            width: 20px;
        }
        ._inp{
            text-align: center;
        }
        .hots {
            width: 500px;
            margin: 20px auto;
        }
        .hots table {
            width: 500px;
            text-align: center;
        }
    </style>
</head>

<body>
    <form>
        商品名称：<input type="text" class="name" /><br />
        单价：<input type="text" class="price" /><br />
        数量：<input type="text" class="number" /><br />
        <input type="button" value="添加" class="add" />
    </form>
    <!-- <button class="add">添加</button> -->
    <table border="1" cellspacing="0" class="cart">
        <thead>
            <tr>
                <th><input id="check" type="checkbox" class="check-all"><label for="check">全选</label></th>
                <th>编号</th>
                <th>商品名称</th>
                <th>单价</th>
                <th>数量</th>
                <th>小计</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody>
            <!-- <tr>
                <td>1</td>
                <td>小米</td>
                <td>2999</td>
                <td>
                    <button>-</button>
                    <input type="text" value="1" style="width:20px" />
                    <button>+</button>
                </td>
                <td>2999</td>
                <td>
                    <button class="remove">删除</button>
                </td>
            </tr> -->
        </tbody>
        <tfoot>
            <tr>
                <td colspan="5">总计</td>
                <td colspan="2" class="allTotal-box">0</td>
            </tr>
        </tfoot>
    </table>
    <div class="hots">
        <h1>推荐商品</h1>
        <table border="1" cellspacing="0">
            <thead>
                <tr>
                    <th>商品名称</th>
                    <th>单价</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <!--  <tr>
                    <td>商品名称100</td>
                    <td>1999</td>
                    <td><button>加入购物车</button></td>
                </tr> -->
            </tbody>
        </table>
    </div>
    <script>
        /* **************************渲染推荐商品********************************  */
        let hots = new Array(10).fill(null).map(function (curr, index) {
            return {
                id: 0,
                name: '商品名称' + (index),
                price: Math.floor(Math.random() * 900) + 99,
            }
        })
        document.querySelector('.hots table tbody').innerHTML = hots.map(function (curr) {
            return `
            <tr>
                <td>${curr.name}</td>
                <td>${curr.price}</td>
                <td><button class="hot-add" data-prod='${JSON.stringify(curr)}''>加入购物车</button></td>
            </tr>
            `/* 在加入购物车按钮上添加了一个H5自定义属性来存放数组中的数据,该属性的值是一个对象，所以需要使用JSON.stringify方法转换成字符串*/
        }).join('')
    </script>

    <script>
        //商品对象数组
        let gods = [{
                id: 1,
                name: "小米手机",
                price: 2999,
                number: 1,
                checked: false
            },
            {
                id: 2,
                name: "华为手机",
                price: 3999,
                number: 1,
                checked: false
            },
            {
                id: 3,
                name: "iphone",
                price: 5999,
                number: 1,
                checked: false
            },
            {
                id: 4,
                name: "vivo手机",
                price: 1999,
                number: 1,
                checked: false
            },
        ];
        //获取页面元素
        const tbody = document.querySelector(".cart tbody");
        const addBtn = document.querySelector(".add");
        const nameInp = document.querySelector(".name");
        const numberInp = document.querySelector(".number");
        const priceInp = document.querySelector(".price");
        //执行渲染表格
        bindHtml();
        //渲染表格函数
        function bindHtml() {
            let str = "";
            gods.forEach(function (item) {
                str += `
            <tr>
                <td><input type="checkbox" class="check-items" ${item.checked?'checked':''} data-id="${item.id}"></td>
                <td>${item.id}</td>
                <td>${item.name}</td>
                <td>${item.price}</td>
                <td>
                    <button class="down numBtn" data-id=${item.id}>-</button>
                    <input type="text" class="_inp" data-id="${item.id}" value="${item.number}" style="width:20px"/>
                    <button class="up numBtn" data-id=${item.id}>+</button>
                </td>
                <td class="total">${item.price * item.number}</td>
                <td>
                    <button class="remove" data-id="${item.id}">删除</button>
                </td>
            </tr>
            `;
            });
            tbody.innerHTML = str;
            /* **************************总价计算********************************  */
            function calcTotal() {
                const total = gods.reduce(function (res, curr) {
                    if (curr.checked) {
                        res += curr.price * curr.number
                        //console.log(res);
                    }
                    return res
                }, 0)
                document.querySelector('.allTotal-box').innerHTML = total.toFixed(2)
            }
            calcTotal()
        }
        /* **************************手动添加商品********************************  */
        //添加函数
        addBtn.onclick = function () {
            const name = nameInp.value.trim();
            const price = Number(priceInp.value.trim());
            const number = Number(numberInp.value.trim());

            if (name === "" || price === "" || number === "") {
                return alert("请完整填写表单！");
            }
            const god = {
                id: 0,
                name: name,
                price: price,
                number: number,
            };
            if (gods.length) {
                god.id = gods[gods.length - 1].id + 1;
            } else {
                god.id = 1;
            }
            /* **************************判断加入地商品是否重复********************************  */
            let res = gods.find(function (curr) {
                return (god.name === curr.name) && (god.price === curr.price)
            })
            if (res !== undefined) { //如果重复则把添加的商品的数量加到重复的数量上
                res.number += Number(god.number)
            } else { //不重复则把添加的数据插入到数组中
                god.checked=document.querySelector('.check-all').checked//插入到数组中的数据的选中状态设置为全选按钮的选中状态
                gods.push(god)
            }
            bindHtml(); //重新渲染添加成功后的数组
            /* 将添加框里的内容置空 */
            nameInp.value = "";
            priceInp.value = "";
            numberInp.value = "";
        };
        /* **************************添加推荐商品********************************  */
        function addHots() {
            document.querySelector('.hots table tbody').addEventListener('click', function (e) {
                if (e.target.classList.contains('hot-add')) {
                    //console.log(e.target.dataset);
                    const currProd = JSON.parse(e.target.dataset.prod)//将模板字符串中的H5自定义属性prod字符串解析成对象
                    //console.log(currProd);
                    currProd.number = 1
                    currProd.checked=document.querySelector('.check-all').checked//将添加到数组里的商品的选中状态设置为全选按钮的选中状态
                    const res = gods.find(function (curr) {//使用find函数查找商品数组中是否存在要添加的推荐商品数据，如果有则返回原数组中商品的数据，没有则返回undefined
                        return currProd.name === curr.name
                    })
                    if (res !== undefined) {//存在重复商品，原商品数量加1
                        res.number += 1
                    } else {//不存在则将商品存入数组
                        if (gods.length) {//给存入的商品编号
                            currProd.id = gods[gods.length - 1].id + 1
                        } else {
                            currProd.id = 1
                        }
                        gods.push(currProd)
                    }
                    bindHtml()
                }
            }, false)
        }
        addHots()
        /* **************************单击事件********************************  */
        function clickEvent() {
            document.querySelector('.cart tbody').addEventListener('click', function (e) {
                if (e.target.classList.contains('remove')) {//使用事件委托给删除按钮绑定点击事件
                    //console.log('点击了删除');
                    //console.log(e.target.dataset.id);
                    let id = Number(e.target.dataset.id)
                    //删除方法一
                    /* for(let i=0;i<gods.length;i++){
                       if(gods[i].id===id){
                           gods.splice(i,1)
                       }
                    } */
                    //删除方法二
                    gods = gods.filter(function (curr) {
                        return curr.id !== id
                    })
                    bindHtml()
                } else if (e.target.classList.contains('up')) {//使用事件委托给数量加按钮绑定点击事件
                    //console.log('点击了数量加');
                    let id = Number(e.target.dataset.id)
                    //数量加方法一
                    /* for(let i=0;i<gods.length;i++){
                        if(gods[i].id===id){
                            gods[i].number+=1
                        }
                    } */
                    //数量加方法二
                    let res = gods.find(function (curr) {
                        return curr.id === id
                    })
                    res.number += 1
                    bindHtml()
                } else if (e.target.classList.contains('down')) {//使用事件委托给数量加按钮绑定点击事件
                    //console.log('点击了数量减');
                    let id = Number(e.target.dataset.id)
                    //数量减方法一
                    /* for(let i=0;i<gods.length;i++){
                        if(gods[i].id===id){
                            if(gods[i].number<=1){
                                return
                            }
                            gods[i].number-=1
                        }
                    } */
                    //数量减方法二
                    let res = gods.find(function (curr) {
                        return curr.id === id
                    })
                    if (res.number <= 1) {
                        return
                    }
                    res.number -= 1
                    bindHtml()
                }
            }, false)
        }
        clickEvent()
        /* **************************change事件********************************  */
        function changeEvent() {
            document.querySelector('.cart').addEventListener('change', function (e) {
                if (e.target.classList.contains('check-all')) {//使用事件委托给全选按钮绑定change事件
                    //console.log(e.target.classList);
                    const _check = e.target.checked
                    //console.log(_check);
                    gods.forEach(function (curr) {
                        curr.checked = _check
                    })
                    bindHtml()
                }
                if (e.target.classList.contains('check-items')) {//使用事件委托给单选按钮绑定change事件
                    //console.log('单选');
                    let id = Number(e.target.dataset.id)
                    let res = gods.find(function (curr) {
                        return curr.id === id
                    })
                    res.checked = !res.checked
                    bindHtml()
                    document.querySelector('.check-all').checked = document.querySelectorAll(
                        '.check-items:checked').length === gods.length
                }
                if (e.target.classList.contains('_inp')) {//使用事件委托给input输入框绑定change事件
                    let id = Number(e.target.dataset.id)
                    //console.log(e.target.value);
                    gods.forEach(function (curr) {
                        //console.log(curr.id);
                        if (id === curr.id) {
                            if (Number(e.target.value) <= 1) {
                                curr.number = 1
                            } else {
                                curr.number = Number(e.target.value)
                            }
                        }
                    })
                }
                bindHtml()
            }, false)
        }
        changeEvent()
    </script>
</body>

</html>